import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 1，高内聚（资源类仅仅把对自己操作的接口暴露出来，即接口分离原则） 低耦合 （数据共享但是各自独立）的前提下 ， 线程操作资源类
 */

// 资源类
class Ticket {
    private int num = 30;
    private Lock lock = new ReentrantLock();
    // 对外暴露操作方法
    public synchronized void saleTicket() {

        // 缩小锁范围，提高并发性
        lock.lock();
        try {
            if (num > 0)
                System.out.println(Thread.currentThread().getName() + "/t卖出第" + num-- + "张票，剩下" + num + "张票");
        }finally {
            lock.unlock();
        }

    }

}

public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        // 匿名内部类,并开启线程


        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 40; i++) {
                    ticket.saleTicket();
                }
            }
        }, "CCC").start();

        new Thread(() -> {
            for (int i = 1; i <= 40; i++) {
                ticket.saleTicket();
            }
        }, "AAA").start();

        new Thread(() -> {
            for (int i = 1; i <= 40; i++) {
                ticket.saleTicket();
            }
        }, "BBB").start();

        new Thread(() -> {
            for (int i = 1; i <= 40; i++) {
                ticket.saleTicket();
            }
        }, "CCC").start();
    }
}
